<template>
    <div>
        <el-dialog title="导入用户" :visible.sync="is_import_excel_dialog_show" :before-close="handleClose" width="500px">
            <div>
                <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" runat="server" @change="changeExcel">
                <p class="personnel-remark">备注：支持excel文件导入，
                    <a download="user" href="http://locales.vkforest.com/user.xlsx">点击下载</a>模板</p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="importExcel">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import user from "@/api/user";

export default {
    name: "import-excel",
    computed: {
        ...mapGetters("personnel", ["is_import_excel_dialog_show"])
    },
    data() {
        return {
            user_excel_data: undefined
        };
    },
    methods: {
        handleClose() {
            document.querySelector("input[type=file]").value = "";
            this.user_excel_data = undefined;
            this.$store.commit(
                "personnel/CHANGE_IS_IMPORT_EXCEL_DIALOG_SHOW",
                false
            );
        },
        importExcel() {
            let params = new FormData();
            if (this.user_excel_data === undefined) {
                this.$message({
                    message: "请添加表格!",
                    type: "warning"
                });
                return;
            }
            params.append("file", this.user_excel_data);
            user
                .importExcel(params)
                .then(res => {
                    this.$message({
                        message: "添加成功!",
                        type: "success"
                    });
                    user
                        .getTableData({ pageNumber: 1 })
                        .then(res => {
                            this.$store.commit(
                                "personnel/CHANGE_USER_LIST",
                                res
                            );
                        })
                        .catch(err => {
                            this.$message.error('刷新失败，请手动刷新');
                        });
                })
                .catch(err => {
                    this.$message.error(err);
                });
            this.handleClose();
        },
        changeExcel(ev) {
            this.user_excel_data = ev.target.files[0];
        }
    }
};
</script>

<style>
.personnel-remark {
    margin-top: 15px;
    margin-bottom: 30px;
}
</style>
